#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>

#include <string>

#include "OSFile.h"
#include "OSCon.h"

using namespace host;
using namespace std;

char OSFile::m_sAppPath[MAX_PATH];

OSFile::OSFile()
{

}

OSFile::~OSFile()
{

}


void OSFile::GetFullPath(const char* sInPath, string& sFullPath)
{
    string strPath = sInPath;

    PathFix(strPath);

    if (strPath[1] != ':')
    {
        sFullPath = m_sAppPath;
        sFullPath+="/";
        sFullPath+=strPath;
    }
    else
    {
        sFullPath = strPath;
    }
}

void OSFile::GetFolder(const char* sPath, string& sFloder)
{
    GetFullPath(sPath, sFloder);

    int nLen = sFloder.find_last_of('/');
    if (nLen != string::npos)
    {
        sFloder = sFloder.substr(0, nLen);
    }
    else
        sFloder = "";
}

void OSFile::Init()
{
    strcpy(m_sAppPath, "./");
}

bool OSFile::PathFix(string& i_sPath)
{
    for (auto i = 0; i < i_sPath.length(); i++)
    {
        if (i_sPath[i] == '\\')
            i_sPath[i] = '/';
    }

    return true;
}

bool OSFile::Mkdir(const char* i_sPath)
{
    if (0 != access(i_sPath, F_OK))
    {
        mkdir(i_sPath, 776);
    }

    return true;
}

bool OSFile::IsExist(const char* i_sPath)
{
    if (0 == access(i_sPath, F_OK))
        return true;

    return false;
}

void OSFile::GetName(const char* sPath, string& sName)
{
    string strPath = sPath;
    int nPos = strPath.find_last_of('/');
    if (nPos != string::npos)
    {
        sName= strPath.substr(nPos + 1);
    }
    else
    {
        sName = strPath;
    }

    nPos = sName.find_last_of('.');
    if (nPos != string::npos)
    {
        sName = sName.substr(0, nPos);
    }
}

void OSFile::GetSuffix(const char* sPath, string& sSuffix)
{
    string strPath = sPath;
    int nPos = strPath.find_last_of('.');
    if (nPos != string::npos)
    {
        sSuffix = strPath.substr(nPos + 1);
    }
    else
    {
        sSuffix = "";
    }
}

bool OSFile::Cover2Folder(const char* i_sPath, string& sFolder)
{
    string inPath = i_sPath;
    string inFull;
    string sName;

    OSFile::PathFix(inPath);
    if (!OSFile::IsExist(inPath.c_str()))
    {
        OSCon::PrintY("file[%s] is not exist", inPath.c_str());
        return -EINVAL;
    }

    OSFile::GetSuffix(inPath.c_str(), sName);
    if (sName != "pcap" && sName != "pcapng")
    {
        OSCon::PrintY("file[%s] is not vaild pcap file", inPath.c_str());
        return -EINVAL;
    }

    OSFile::GetName(inPath.c_str(), sName);
    OSFile::GetFullPath(inPath.c_str(), inFull);
    OSFile::GetFolder(inFull.c_str(), sFolder);
    if (sFolder.at(sFolder.length() - 1) != '/')
        sFolder += '/';
    sFolder += sName;

    return true;
}
